<!-- 投喂条件配置 -->
<template>
  <BaseMainSlot>
    <template v-slot:content>
      <el-form ref="ruleForm" label-position="left" :model="formData" :rules="rules">
        <section class="variety section-box">
          
          <el-form-item label="选择品种" prop="varietyId" class="changeFish">
            <div class="variety-content" id="nav">
              <div class="variety-content-btns" :class="{ 'variety-content-btn-selected': activeIndex === index }"
                v-for="(item, index) of varietyList" :key="item.fishVarietyId" @click="varietyChange(item, index)">
                <span>{{ item.varietyName }}</span>
              </div>
            </div>
           <div class="multi">
              <span @click="scroll('leftMost')"  class="el-icon-d-arrow-left"></span>
              <span @click="scroll('left')"      class="el-icon-caret-left"  ></span>
              <span @click="scroll('right')"     class="el-icon-caret-right"  ></span>
              <span @click="scroll('rightMost')" class="el-icon-d-arrow-right" ></span>
            </div>
          </el-form-item>

          <el-form-item label="选择数据项" prop="dataTypeId">
            <el-select filterable clearable v-model="formData.dataTypeId" clearable filterable placeholder="请选择" @change="dataItemChange">
              <el-option v-for="(item, index) of dataItemList" :key="index + 'pond'" :label="item.dataTypeName"
                :value="item.dataTypeId" />
            </el-select>
          </el-form-item>
        </section>

        <section class="form section-box">
          <!-- 左区间 -->
          <div class="form-item-row">
            <el-form-item label="如果 :" prop="bottomLimit.rangeMax"
              :rules="{ required: true, message: '请规范填写', trigger: 'blur' }">
              <el-select filterable clearable v-model="formData.bottomLimit.rangeMaxSymbol" clearable filterable placeholder="请选择"
                style="width:90px;">
                <el-option label="<" value="<" />
                <el-option label="<=" value="<=" />
              </el-select>
              <el-input @change="handleInput(formData.bottomLimit, 'rangeMax')" min="0"
                v-model="formData.bottomLimit.rangeMax" style="width:100px" />
            </el-form-item>
            <el-form-item label="投喂百分比 :" prop="bottomLimit.ratio"
              :rules="{ required: true, message: '请规范填写', trigger: 'blur' }">
              <el-input v-model="formData.bottomLimit.ratio"
                @change="formData.bottomLimit.ratio < 0 || formData.bottomLimit.ratio > 100 ? formData.bottomLimit.ratio = 0 : ''"
                style="width:150px">
                <template slot="append">%</template>
              </el-input>
            </el-form-item>
          </div>
          <!-- 中间 -->
          <div class="form-item-row" v-for="(item, index) of formData.centerLimit" :key="index">
            <el-form-item label="如果 :" :prop="'centerLimit.' + index + '.rangeMin'"
              :rules="{ required: true, message: '请规范填写', trigger: 'blur' }">
              <el-select filterable clearable v-model="item.rangeMinSymbol" clearable filterable placeholder="请选择" style="width:90px;">
                <el-option label=">" value=">" />
                <el-option label=">=" value=">=" />
              </el-select>
              <el-input @change="handleInput(item, 'rangeMin')" min="0" v-model="item.rangeMin" style="width:100px" />
            </el-form-item>
            <el-form-item label="且 :" :prop="'centerLimit.' + index + '.rangeMax'"
              :rules="{ required: true, message: '请规范填写', trigger: 'blur' }">
              <el-select filterable clearable v-model="item.rangeMaxSymbol" clearable filterable placeholder="请选择" style="width:90px;">
                <el-option label="<" value="<" />
                <el-option label="<=" value="<=" />
              </el-select>
              <el-input @change="handleInput(item, 'rangeMax')" min="0" v-model="item.rangeMax" style="width:100px" />
            </el-form-item>
            <el-form-item label="投喂百分比 :" :prop="'centerLimit.' + index + '.ratio'"
              :rules="{ required: true, message: '请规范填写', trigger: 'blur' }">
              <el-input v-model="item.ratio" @change="item.ratio < 0 || item.ratio > 100 ? item.ratio = 0 : ''"
                style="width:150px">
                <template slot="append">%</template>
              </el-input>
            </el-form-item>
            <div class="btn-group">
              <div class="del-btn" v-show="formData.centerLimit.length !== 1" @click="delRow(index)">
                <i class="el-icon-minus"></i>
              </div>
              <div class="add-btn" v-show="index === formData.centerLimit.length - 1" @click="addRow()">
                <i class="el-icon-plus"></i>
              </div>
            </div>
          </div>
          <!-- 右区间 -->
          <div class="form-item-row">
            <el-form-item label="如果 :" prop="topLimit.rangeMin"
              :rules="{ required: true, message: '请规范填写', trigger: 'blur' }">
              <el-select filterable clearable v-model="formData.topLimit.rangeMinSymbol" clearable filterable placeholder="请选择"
                style="width:90px;">
                <el-option label=">" value=">" />
                <el-option label=">=" value=">=" />
              </el-select>
              <el-input @change="handleInput(formData.topLimit, 'rangeMin')" min="0" v-model="formData.topLimit.rangeMin"
                style="width:100px" />
            </el-form-item>
            <el-form-item label="投喂百分比 :" prop="topLimit.ratio"
              :rules="{ required: true, message: '请规范填写', trigger: 'blur' }">
              <el-input v-model="formData.topLimit.ratio"
                @change="formData.topLimit.ratio < 0 || formData.topLimit.ratio > 100 ? formData.topLimit.ratio = 0 : ''"
                style="width:150px">
                <template slot="append">%</template>
              </el-input>
            </el-form-item>
          </div>
          <div class="preview">
            <span>投喂条件预览:</span>
            <div class="preview-row">
              <span>{{ `如果${formData.dataItemType ? formData.dataItemType : ''}${formData.bottomLimit.rangeMinSymbol ?
                formData.bottomLimit.rangeMinSymbol
                :
                ''}${formData.bottomLimit.rangeMin ? formData.bottomLimit.rangeMin :
                  ''}${formData.bottomLimit.rangeMaxSymbol && formData.bottomLimit.rangeMax ?
                    formData.bottomLimit.rangeMaxSymbol + formData.bottomLimit.rangeMax + ',' :
                    ''}${formData.bottomLimit.ratio ?
                      '投喂率为' + formData.bottomLimit.ratio + '%。' : ''}` }}</span>
            </div>
            <div class="preview-row" v-for="(item, index) of formData.centerLimit" :key="index">
              <span>{{ `如果${formData.dataItemType ? formData.dataItemType : ''}${item.rangeMinSymbol ? item.rangeMinSymbol
                :
                ''}${item.rangeMin ? item.rangeMin : ''}${item.rangeMaxSymbol && item.rangeMax ?
                  '并且' + item.rangeMaxSymbol + item.rangeMax + ',' : ''}${item.ratio ?
                    '投喂率为' + item.ratio + '%。' : ''}` }}</span>
            </div>
            <div class="preview-row">
              <span>{{ `如果${formData.dataItemType ? formData.dataItemType : ''}${formData.topLimit.rangeMinSymbol ?
                formData.topLimit.rangeMinSymbol
                :
                ''}${formData.topLimit.rangeMin ? formData.topLimit.rangeMin : ''}${formData.topLimit.rangeMaxSymbol &&
                  formData.topLimit.rangeMax ?
                  '并且' + formData.topLimit.rangeMaxSymbol + formData.topLimit.rangeMax + ',' : ''}${formData.topLimit.ratio
                    ?
                    '投喂率为' + formData.topLimit.ratio + '%。' : ''}` }}</span>
            </div>
          </div>
          <div class="dialog-footer">
            <el-button type="primary" class="savebtn" @click="add()">确认添加</el-button>
            <el-button class="cancelbtn" @click="cancel()">取 消</el-button>
          </div>
        </section>
      </el-form>
      <section class="result section-box">
        <div class="result-title">已添加条件</div>
        <div class="result-row" v-for="(item, index) of configuredList" :key="item.feedWorkEnvConfigId">
          <span style="margin-left:10px;color:#000;font-size:18px;">配置{{ index + 1 }}: {{ item.varietyName }}</span>
          <div class="result-row-content" v-for="detailItem of item.feedWorkEnvConfigDetailList"
            :key="detailItem.feedWorkEnvConfigDetailId">
            <span>{{ `如果${item.dataItemType ? item.dataItemType : ''}${detailItem.rangeMinSymbol ?
              detailItem.rangeMinSymbol : ''}${detailItem.rangeMin ? + detailItem.rangeMin :
                ''}${detailItem.rangeMaxSymbol ? detailItem.rangeMin && detailItem.rangeMax ? '并且' +
                  detailItem.rangeMaxSymbol
                  : detailItem.rangeMaxSymbol : ''}${detailItem.rangeMax ?
                    detailItem.rangeMax : ''},投喂率为${detailItem.ratio ? detailItem.ratio : '0'}%。` }}</span>
          </div>
          <div class="result-row-del-btn" @click="delOne(item)"><span>删除</span></div>
          <el-divider></el-divider>
        </div>
      </section>
    </template>
  </BaseMainSlot>
</template>

<script>
import BaseMainSlot from "@/components/BaseMainSlot/kong-new2.vue";

import DataItemManageApi from "@/api/basic-info-manage/data-type-manage";
import VarietyApi from "@/api/basic-info-manage/fishVariety";
import ConditionConfigApi from "@/api/feeding-manegement/feeding-condition-config";
export default {
  name: "FeedingConditionConfig",
  components: { BaseMainSlot },
  mixins: [],
  data () {
    var checkName = (rule, value, callback) => {
      console.log(rule)
      if (!value) {
        return callback(new Error('姓名不能为空'));
      } else if (!nameZz.test(value)) {
        return callback(new Error('姓名格式不正确'))
      } else {
        callback();
      }
    }
    return {
      // 控制弹出框显示隐藏
      formData: {
        bottomLimit: {},
        centerLimit: [{}],
        topLimit: {},
      },
      rules: {
        varietyId: [{ required: true, message: '请选择品种', trigger: 'click' }],
        dataTypeId: [{ required: true, message: '请选择数据项', trigger: 'change' }],
      },
      dataItemList: [],
      varietyList: [],
      configuredList: [],
      waterTemperatureCondition: {// 水温初始化条件
        bottomLimit: {
          rangeMaxSymbol: '<',
          rangeMax: 10,
          ratio: 50
        },
        centerLimit: [
          {
            rangeMinSymbol: '>=',
            rangeMin: 10,
            rangeMaxSymbol: '<=',
            rangeMax: 20,
            ratio: 65
          },
          {
            rangeMinSymbol: '>',
            rangeMin: 20,
            rangeMaxSymbol: '<=',
            rangeMax: 30,
            ratio: 100
          },
        ],
        topLimit: {
          rangeMinSymbol: '>',
          rangeMin: 30,
          ratio: 50
        }
      },
      PHCondition: {// 酸碱度初始化条件
        bottomLimit: {
          rangeMaxSymbol: '<',
          rangeMax: 6.5,
          ratio: 50
        },
        centerLimit: [
          {
            rangeMinSymbol: '>=',
            rangeMin: 6.5,
            rangeMaxSymbol: '<=',
            rangeMax: 8.5,
            ratio: 100
          },
        ],
        topLimit: {
          rangeMinSymbol: '>',
          rangeMin: 8.5,
          ratio: 50
        }
      },
      oxygenCondition: {// 酸碱度初始化条件
        bottomLimit: {
          rangeMaxSymbol: '<',
          rangeMax: 2,
          ratio: 0
        },
        centerLimit: [
          {
            rangeMinSymbol: '>=',
            rangeMin: 2,
            rangeMaxSymbol: '<=',
            rangeMax: 4,
            ratio: 60
          },
        ],
        topLimit: {
          rangeMinSymbol: '>',
          rangeMin: 4,
          ratio: 100
        }
      },
      activeIndex: undefined,
      showAddEditDialog: false,
    };
  },
  computed: {
  },
  watch: {},
  created () {
  },
  mounted () {
    this.queryDataItem()
    this.queryVariety()
    this.queryAllConfigured()
  },
  methods: {
     scroll(scroll) {
      let content = document.querySelector("#nav");
      // 到最左侧
      if (scroll=='leftMost') {
        content.scrollLeft -= 50000;  
      }
      // 向左侧滚动一定距离
      if (scroll=='left') {
        content.scrollLeft -= 300; 
      }
      // 向右侧滚动一定距离
      if (scroll=='right') {
        content.scrollLeft += 300; 
      }
      // 到最右侧
      if (scroll=='rightMost') {
        content.scrollLeft += 50000; 
      }
    },
    handleInput (data, name) {
      data[name] < 0 && (data[name] = '')
    },
    queryAllConfigured () {
      ConditionConfigApi.queryByCondition().then(res => {
        if (res.data) this.configuredList = res.data;
      })
    },
    queryVariety () {
      VarietyApi.queryByCondition().then(res => {
        this.varietyList = res.data;
      })
    },
    queryDataItem () {
      DataItemManageApi.queryByCondition().then(res => {
        if (res.data) this.dataItemList = res.data;
      });
    },
    varietyChange (item, index) {
      if (item.fishVarietyId) {
        this.$set(this.formData, 'varietyId', item.fishVarietyId);
        this.activeIndex = index;
        this.$refs['ruleForm'].clearValidate('varietyId')
      }
    },
    dataItemChange (e) {
      this.dataItemList.find((item) => {
        if (item.dataTypeId === e) {
          if (item.dataTypeName) this.$set(this.formData, 'dataItemType', item.dataTypeName)
          // console.log(this.formData);
          if (item.dataTypeName === "水温") {
            this.$set(this.formData, 'bottomLimit', this.waterTemperatureCondition.bottomLimit)
            this.$set(this.formData, 'centerLimit', this.waterTemperatureCondition.centerLimit)
            this.$set(this.formData, 'topLimit', this.waterTemperatureCondition.topLimit)
          } else if (item.dataTypeName === "PH值") {
            this.$set(this.formData, 'bottomLimit', this.PHCondition.bottomLimit)
            this.$set(this.formData, 'centerLimit', this.PHCondition.centerLimit)
            this.$set(this.formData, 'topLimit', this.PHCondition.topLimit)
          } else if (item.dataTypeName === "含氧量") {
            this.$set(this.formData, 'bottomLimit', this.oxygenCondition.bottomLimit)
            this.$set(this.formData, 'centerLimit', this.oxygenCondition.centerLimit)
            this.$set(this.formData, 'topLimit', this.oxygenCondition.topLimit)
          }
        }
      })
    },
    addRow () {
      this.formData.centerLimit.push({})
    },
    delRow (index) {
      this.formData.centerLimit.splice(index, 1)
    },
    // 单个删除
    delOne (data) {
      this.$confirm("此操作将永久删除该项, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
        
      })
        .then(() => {
          ConditionConfigApi.delById({ id: data.feedWorkEnvConfigId }).then(res => {
            if (res.success === true) {
              this.$message.success("删除成功!");
              this.queryAllConfigured();
            }
          });
        })
        .catch(() => {
          this.resetActionBar();
          this.$message({
            type: "info",
            message: "已取消删除"
          });
        });
    },
    // 添加
    add () {
      this.$refs['ruleForm'].validate(valid => {
        if (valid) {
          this.formData.feedWorkEnvConfigDetailList = [
            this.formData.bottomLimit,
            ...this.formData.centerLimit,
            this.formData.topLimit
          ]
          delete this.formData.bottomLimit
          delete this.formData.centerLimit
          delete this.formData.topLimit
          ConditionConfigApi.add(this.formData).then(res => {
            if (res.success === true) {
              this.$refs['ruleForm'].clearValidate()
              this.$message.success("添加成功!");
              this.queryAllConfigured()
              this.cancel()
            } else {
              this.$message.warning(res.message);
              this.cancel()
            }
          })
        } else {
          return false;
        }
      });
    },
    cancel () {
      this.formData = {
        bottomLimit: {},
        centerLimit: [{}],
        topLimit: {},
      }
      this.activeIndex = undefined;
      this.$nextTick(() => {
        this.$refs['ruleForm'].clearValidate('dataTypeId')
      })
    },
  }
};
</script>

<style lang="scss" scoped>
@import "../style/index.scss";

.preview {
  color: #004486;
  font-weight: 400;
  font-size: 18px;

  &-row {
    margin: 10px;
  }
}

.form {
  padding: 10px;
}

.result-row {
  display: flex;
  justify-content: center;
  flex-wrap: wrap;
  flex-direction: column;
}

.result-row-del-btn {
  position: absolute;
  top: 50%;
  right: 20px;
  transform: translateY(-50%);
  width: 59px;
  height: 32px;
  border: 1px solid #0480FB;
  border-radius: 5px;
  font-size: 16px;
  color: #0480FB;
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
}
/* 选择品种 */
.changeFish{
  margin-bottom: 30px;
  /* 品种行 */
  ::v-deep .el-form-item__content{
    width: calc(100%);
  }
  .variety-content{
    overflow-x: scroll;
    overflow-y: hidden;
  }
  /* 横向移动功能 */
  .multi{
    position: absolute;
    margin-left: 90px;
    span{
      font-size: 24px;
      margin-right: 10px;
      cursor: pointer;
    }
  }
}
</style>
